import React, { useEffect, useState, useRef, createContext, useContext } from 'react'
import { Tooltip } from 'antd'
import css from './runtime.less'

export default ({ data, inputs, slots, env, outputs }: any) => {
  const [text, setTextFn] = useState(data.text || '文本')
  const [hover, setHoverFn] = useState(false)
  const [over, setOverFn] = useState(false)
  const [inputStyle, setInputStyle] = useState<any>({})
  const boxDom = useRef<HTMLDivElement>(null)
  const fadeDom = useRef<HTMLDivElement>(null)
  const realDom = useRef<HTMLDivElement>(null)

  inputs['text']?.((_text: string, relOutput: any) => {
    setTextFn(_text || '文本')
    relOutput?.['textInputDone']?.(_text)
  })

  inputs['style']?.((style: any, relOutput: any) => {
    setInputStyle(style)
    relOutput?.['textInputDone']?.(style)
  })

  useEffect(() => {
    if (!env.runtime) {
      setTextFn(data.text || '文本')
    }
  }, [data.text])

  useEffect(() => {
    const dom = boxDom.current
    const style = inputStyle
    if (!dom || !style) return
    if (typeof style != 'object') return
    for (const [k, v] of Object.entries<string>(style)) {
      if (k.startsWith('--')) {
        dom.style.setProperty(k, v)
      } else {
        dom.style[k] = v
      }
    }
  }, [boxDom.current, inputStyle])

  useEffect(() => {
    if (!realDom.current || !fadeDom.current || !boxDom.current) {
      return () => {}
    }
    const resizeObserver = new ResizeObserver(() => {
      setOverFn(fadeDom.current!.scrollWidth > realDom.current!.clientWidth)
    })
    resizeObserver.observe(boxDom.current)
    return () => {
      resizeObserver.disconnect()
    }
  }, [realDom, fadeDom, boxDom])

  return (
    <div ref={boxDom} className={css.box}>
      <Tooltip open={hover && (over || Boolean(data.showAllTime))} title={text}>
        <div ref={realDom} className={css.real} onMouseEnter={() => setHoverFn(true)} onMouseLeave={() => setHoverFn(false)}>
          {text}
        </div>
      </Tooltip>
      <div ref={fadeDom} className={css.fade}>
        {text}
      </div>
    </div>
  )
}
